import { Context } from "koa";
import emitter from "../utils/emitter";
import logger from "../utils/logger";
import { HttpStatus } from "./responseHandler";

// 跨域处理
export default async (ctx: Context, next) => {
  const origin = ctx.headers.origin || ctx.request.origin;
  ctx.set('Access-Control-Allow-Credentials', 'true');
  ctx.set('Access-Control-Allow-Origin', origin);
  // 预检
  if (ctx.method === 'OPTIONS') {
    // authorization允许header里传token
    ctx.set('Access-Control-Allow-Headers', 'authorization,x-requested-with,accept,origin, content-type');
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    ctx.status = HttpStatus.OK;
    return;
  }
  await next();
  // 白名单处理 如需要限制来源即可放开这个设置 白名单在application.yml里设置
  // if (global.config.get('whiteList').includes(origin)) {
  //   await next();
  // } else {
  //   emitter.emit('errorResponse', ctx, HttpStatus.FORBIDDEN, '未认证,无权访问');
  // }
};
